package org.example.socketdemos;

import org.example.utils.LogUtils;
import sun.nio.ch.IOUtil;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.InetSocketAddress;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;

public class ClientSocketDemo {
    public static void main(String[] args) throws IOException {
        SocketChannel socketChannel = SocketChannel.open();

        socketChannel.configureBlocking(false);

        socketChannel.connect(new InetSocketAddress("localhost", 8081));

        // 自旋是否连接
        while (!socketChannel.finishConnect()) {

        }

        LogUtils.info("建立连接");

        URL resource = ClientSocketDemo.class.getResource("/filedemos/1.txt");
        RandomAccessFile raFile = new RandomAccessFile(resource.getFile(), "rw");
        File originFile = new File(resource.getFile());
        FileChannel fileChannel = raFile.getChannel();

        ByteBuffer buffer = ByteBuffer.allocate(1024);

        // 发送文件名的长度
        buffer.putInt(originFile.getName().length());
        LogUtils.info("发送文件名长度：" + originFile.getName().getBytes().length);
        buffer.flip();
        socketChannel.write(buffer);

        // 发送文件名
        buffer.clear();
        buffer.put(originFile.getName().getBytes());
        LogUtils.info("发送文件名：" + originFile.getName());
        buffer.flip();
        socketChannel.write(buffer);

        // 发送文件大小
        buffer.clear();
        buffer.putLong(fileChannel.size());
        LogUtils.info("发送文件大小：" + fileChannel.size());
        buffer.flip();
        socketChannel.write(buffer);

        // 发送文件内容
        buffer.clear();

        LogUtils.info("开始发送文件内容");
        int num = -1;
        while ((num = fileChannel.read(buffer)) > 0) {
            buffer.flip();
            socketChannel.write(buffer);
            buffer.clear();
        }

        socketChannel.shutdownOutput();
        LogUtils.info("客户端关闭连接");
        socketChannel.close();
    }
}
